package org.sampleSpringFramework.mvc.render.impl;

import com.google.gson.Gson;
import org.sampleSpringFramework.mvc.processor.RequestProcessorChain;
import org.sampleSpringFramework.mvc.render.ResultRender;

import java.io.PrintWriter;

/**
 * 请求Json时使用的结果渲染器
 */
public class JsonResultRender implements ResultRender {

	// 接受带有@ResponseBody方法的返回值，使用Gson工具将其转换成json格式的数据
	private Object result;

    public JsonResultRender(Object result) {
    	this.result = result;
    }

    @Override
	public void render(RequestProcessorChain requestProcessorChain) throws Exception {
    	// 1、设置内容，编码
		requestProcessorChain.getResponse().setContentType("application/json");
		requestProcessorChain.getResponse().setCharacterEncoding("UTF-8");
		// 2、获取响应流，将Gson转换的json数据写入，然后刷新
		PrintWriter writer = requestProcessorChain.getResponse().getWriter();
		Gson gson = new Gson();
		writer.write(gson.toJson(result));
		writer.flush();
	}
}
